import axios from 'axios'
import Vue from 'vue'
import qs from 'qs'
import store from '../store/index'
import Router from 'vue-router'
import { router } from '../router/index'
import { getRand } from '@/utils/random'
import { signParams } from '@/utils/sign'
import { Modal } from 'iview'
import api from '@/api/api'
axios.defaults.baseURL = process.env.NODE_ENV == 'production' ? api.root : api.testRoot;

/**
 * 请求拦截器
 * 
 */
axios.interceptors.request.use(config => {

    var ct = config.headers['Content-Type'];

    //application/x-www-form-urlencoded
    // if(ct=='application/json'||ct=="text/plain")
    // {
    //     return config;
    // }

    let appKey = process.env.VUE_APP_APPKEY;
    let sessionKey = localStorage.getItem('sessionKey');
    let token = localStorage.getItem('token');
    let params = {
        nonceStr: getRand()
    };
    if (sessionKey && sessionKey != '' && sessionKey != undefined) {
        params.sessionKey = sessionKey;
    }
    if (token && token != '' && token != undefined) {
        params.token = token;
    }
    for (let key in config.data) {
        params[key] = config.data[key];
    }
    params = signParams(params, appKey);
    config.data = qs.stringify(params);
    return config;
}, error => {

    Promise.reject(error);
})



axios.interceptors.response.use(response => {
        let res = response.data;

        switch (res.status) {
            case 0:

                break;
            case -2:
                Modal.confirm({
                    title: '提醒',
                    content: '<p>登录已超时，请重新登录！</p>',
                    onOk: () => {
                        store.dispatch('loginOutClear').then(() => {

                            router.push({ name: "Login" })
                        });
                    },
                    onCancel: () => {
                        store.dispatch('loginOutClear').then(() => {
                            router.push({ name: "Login" })
                        });
                    }
                });
                break;
        }

        return response.data;
    },
    error => {



        return Promise.reject(error)
    }
);

export default axios